package com.cool.cloud.controller;

import com.cool.cloud.entity.*;
import com.cool.cloud.utils.LogUtils;
import com.cool.cloud.utils.QRCodeUtil;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description 信息管理控制器（日志、分享记录、离线下载等）
 * @Author laijunji
 * @Date 18:19 2020/2/25
 * @Param * @param null
 * @return
 **/
@Controller
public class InfoController extends BaseController {
    private Logger logger = LogUtils.getInstance(InfoController.class);

    /**
     * @return java.lang.String
     * @Description 我的分享记录页面
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @GetMapping("/myshare")
    public String myshare() {
        return "main/myshare";
    }

    /**
     * @return java.lang.String
     * @Description 我的分享记录信息
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @ResponseBody
    @GetMapping("/getSharedate")
    public List<FileShare> getSharedate() {
        //获得分享记录信息
        return shareFileService.queryByUserId(loginUser.getUserId());
    }

    /**
     * @return java.lang.String
     * @Description 滚动图信息页面
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @GetMapping("/slider-picture")
    public String sliderPicture() {
        return "main/slider-picture";
    }

    /**
     * @return java.lang.String
     * @Description 滚动图信息
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @ResponseBody
    @GetMapping("/getSliderPicDate")
    public List<SliderPicture> getSliderPicDate() {
        //获得分享记录信息
        return sliderPictureService.queryAll();
    }

    /**
     * @return java.lang.String
     * @Description 滚动图信息删除
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param
     **/
    @ResponseBody
    @RequestMapping("/delSliderPic")
    public HashMap<String, String> delSliderPic(Integer id, String url) {
        HashMap<String, String> rs = new HashMap();
        String name = url.substring(url.lastIndexOf("/") + 1);
        if (sliderPictureService.delete(id) > 0) {
            //删除具体路径下的文件
            try {
                String baseurl = ResourceUtils.getURL("classpath:").getPath() + "static/sliderPicture";
                File file = new File(URLDecoder.decode(baseurl + File.separator + name, "UTF-8"));
                FileUtils.forceDelete(file);
            } catch (FileNotFoundException e) {
                logger.info("滚动图文件不存在：" + name);
            } catch (IOException e) {
                logger.info("滚动图文件删除失败：" + name);
            }
            rs.put("status", "success");
        } else {
            rs.put("status", "fail");
        }
        return rs;
    }

    /**
     * @return void
     * @Description 上传滚动图文件
     * @Author laijunju
     * @Date 23:14 2020/3/9
     * @Param [files]
     **/
    @PostMapping("/uploadSliderPic")
    @ResponseBody
    public HashMap<String, String> uploadTempFile(@RequestParam("file") MultipartFile file) {
        HashMap<String, String> rs = new HashMap();
        String name = file.getOriginalFilename().replaceAll(" ", "");
        try {
            String baseurl = ResourceUtils.getURL("classpath:").getPath() + "static/sliderPicture";
            File newFile = new File(URLDecoder.decode(baseurl, "UTF-8"));
            if (!newFile.exists() && !newFile.isDirectory()) {
                newFile.mkdirs();
            }
            File files = new File(newFile, name);
            file.transferTo(files);
        } catch (Exception e) {
            logger.error("文件保存报错" + e);
            rs.put("status", "fail");
        }
        SliderPicture sp = new SliderPicture();
        sp.setImageName(name);
        sp.setImagePath("./sliderPicture/" + name);
        sliderPictureService.add(sp);
        rs.put("status", "success");
        return rs;
    }

    /**
     * @return java.lang.String
     * @Description 我的分享记录批量删除
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @ResponseBody
    @RequestMapping("/batchDelShare")
    public HashMap<String, String> batchDelShare(@RequestParam String ids) {
        String[] shareIds = ids.split(",");
        HashMap<String, String> rs = new HashMap();
        if (shareFileService.batchDelete(shareIds) > 0) {
            rs.put("status", "success");
        } else {
            rs.put("status", "fail");
        }
        return rs;
    }

    /**
     * @return java.lang.String
     * @Description 我的分享记录下载链接
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @ResponseBody
    @RequestMapping("/getQrcode")
    public Map<String, Object> getQrcode(String f, String profixurl) {
        Map<String, Object> map = new HashMap<>();
        FileShare share = shareFileService.queryByFileId(Integer.valueOf(f));
        String url = "";
        try {
            String path = request.getSession().getServletContext().getRealPath("/user_img/");
            url = profixurl + "share?code=" + share.getUrl() + "&f=" + share.getFileId() + "&flag=1&p=unknown";
            File targetFile = new File(path, "");
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            File file = new File(path, share.getFileId() + ".jpg");
            if (!file.exists()) {
                //文件不存在,开始生成二维码并保存文件
                OutputStream os = new FileOutputStream(file);
                QRCodeUtil.encode(url, "/static/img/CoolCloudLogo.png", os, true);
                os.close();
            }
            map.put("imgPath", "user_img/" + share.getFileId() + ".jpg");
            map.put("password", share.getUnDecrypt());
            map.put("url", url);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    /**
     * @return java.lang.String
     * @Description 后台任务记录页面
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @GetMapping("/backgroundwork")
    public String backgroupwork() {
        return "main/backgroundwork";
    }

    /**
     * @return java.lang.String
     * @Description 后台任务查询
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @ResponseBody
    @GetMapping("/bgworkdate")
    public List<BGWork> bgworkdate() {
        //获得我创建的后台任务
        return bgWorkService.queryByUserId(loginUser.getUserId());
    }

    /**
     * @return java.lang.String
     * @Description 后台任务查询
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @ResponseBody
    @RequestMapping("/createBGWork")
    public HashMap<String, String> createBGWork(String url, String sheduletime, Integer sec) throws Exception {
        Date sdltime = new SimpleDateFormat("yyyy-MM-dd hh:mm").parse(sheduletime);
        BGWork bgwork = new BGWork().setCreateTime(new Date()).setCreateUserid(loginUser.getUserId()).setDlUrl(url).setSheduleTime(sdltime);
        HashMap<String, String> rs = new HashMap();
        //创建download目录
        //设置文件夹信息
        FileFolder folder = new FileFolder().setFileStoreId(loginUser.getFileStoreId()).setTime(new Date()).setFileFolderName("Download").setParentFolderId(0);
        //获得当前目录下的所有文件夹,检查当前文件夹是否已经存在
        List<FileFolder> fileFolders = fileFolderService.getRootFoldersByFileStoreId(loginUser.getFileStoreId());
        boolean noexist = true;
        for (int i = 0; i < fileFolders.size(); i++) {
            FileFolder fileFolder = fileFolders.get(i);
            if (fileFolder.getFileFolderName().equals(folder.getFileFolderName())) {
                noexist = false;
                break;
            }
        }
        //向数据库写入数据
        int folderid = 0;
        if (noexist) {
            fileFolderService.addFileFolder(folder);
            folderid = folder.getFileFolderId();
        } else {
            folderid = fileFolderService.getFileFolderIdByFileFolderNameAndStoreId("Download", loginUser.getFileStoreId());
        }
        //执行插入数据
        if (bgWorkService.insert(bgwork) > 0) {
            //异步执行任务
            bgWorkService.excute(bgwork, sec, folderid, loginUser.getFileStoreId());
            rs.put("status", "success");
        } else {
            rs.put("status", "fail");
        }
        return rs;
    }

    /**
     * @return java.lang.String
     * @Description 我的任务批量删除
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @ResponseBody
    @RequestMapping("/batchDelBGWork")
    public HashMap<String, String> batchDelBGWork(@RequestParam String pks) {
        String[] workpks = pks.split(",");
        HashMap<String, String> rs = new HashMap();
        if (bgWorkService.batchDelete(workpks) > 0) {
            rs.put("status", "success");
        } else {
            rs.put("status", "fail");
        }
        return rs;
    }

    /**
     * @return java.lang.String
     * @Description 存储策略管理页面
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @GetMapping("/manage-storage")
    public String manageStorage() {
        return "main/manage-storage";
    }

    /**
     * @return json
     * @Description 存储策略查询
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @ResponseBody
    @GetMapping("/getSizeTypedate")
    public List<SizeType> getSizeTypedate() {
        //获得所有存储策略
        return sizeTypeService.queryAll();
    }

    /**
     * @return json
     * @Description 存储策略修改
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @ResponseBody
    @GetMapping("/editSizeType")
    public HashMap<String, String> editSizeType(Integer type, Integer size) {
        HashMap<String, String> rs = new HashMap();
        if (sizeTypeService.update(SizeType.builder().type(type).size(size).build()) > 0) {
            rs.put("status", "success");
        } else {
            rs.put("status", "fail");
        }
        return rs;
    }

    /**
     * @return java.lang.String
     * @Description 我的钱包
     * @Author laijunji
     * @Date 15:17 2020/2/26
     * @Param []
     **/
    @GetMapping("/wallet")
    public String externalEditword() {
        return "main/wallet";
    }

    /**
     * @return java.lang.String
     * @Description 条件查询后返回文件总览页面
     * @Author laijunji
     * @Date 23:28 2020/2/10
     * @Param [fId, fName, error, map]
     **/
    @GetMapping("/search")
    public String toFileStorePage(String fileName, Map<String, Object> map, Integer cur) {
        //分页
        ArrayList<Integer> page = new ArrayList();
        //获取当前查询的页数，如果为空，默认为1
        cur = (cur == null || cur <= 0) ? 1 : cur;
        List<FileFolder> folders = null;
        //包含的文件
        List<MyFile> files = myFileService.getFilesBySearch(loginUser.getFileStoreId(), fileName);
        ArrayList<MyFile> allObj = new ArrayList<>();
        allObj.addAll(files);
        int pagenum = (int) Math.ceil(allObj.size() / 8.0);
        page.add(pagenum);
        cur = cur > pagenum ? pagenum : cur;
        page.add(cur);
        files = new ArrayList<>();
        List<MyFile> objects = new ArrayList<>();
        if (allObj.size() <= cur * 8 && allObj.size() != 0) {
            objects = allObj.subList((cur - 1) * 8, allObj.size());
        } else if (allObj.size() > cur * 8 && allObj.size() != 0) {
            objects = allObj.subList((cur - 1) * 8, (cur - 1) * 8 + 8);
        }
        files.addAll(objects);
        //当前文件夹信息
        FileFolder nowFolder = null;
        //当前文件夹的相对路径
        List<FileFolder> location = new ArrayList<>();
        //代表当前为根目录
        nowFolder = FileFolder.builder().fileFolderId(0).build();
        location.add(nowFolder);
        Collections.reverse(location);
        map.put("page", page);
        map.put("permission", fileStoreService.getFileStoreByUserId(loginUser.getUserId()).getPermission());
        map.put("files", files);
        map.put("folders", folders);
        map.put("nowFolder", nowFolder);
        map.put("location", location);
        session.setAttribute("searchName", fileName);
        return "main/file-all";
    }

}
